<template>
  <!--完成  -->
  <div style="width: 80%">
    <div style="margin-bottom: 30px">新增用户</div>
    <el-form :inline="true" :model="form" :rules="rules" ref="ruleForm" label-width="100px">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="form.name" placeholder="请输入姓名"></el-input>
      </el-form-item>
      <el-form-item label="学生id" prop="studentId">
        <el-input v-model="form.studentId" placeholder="请输入学生id"></el-input>
      </el-form-item>
      <el-form-item label="专业" prop="major">
        <el-input v-model="form.major" placeholder="请输入学生专业"></el-input>
      </el-form-item>
      <el-form-item label="年级" prop="grade">
        <el-input v-model="form.grade" oninput="value=value.replace(/\D/g,'')" placeholder="请输入学生年级"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="form.password" placeholder="请输入密码"></el-input>
      </el-form-item>
    </el-form>
    <div style="text-align: center; margin-top: 30px">
      <el-button type="primary" @click="save" size="medium">提交</el-button>
    </div>
  </div>
</template>

<script>
import request from "@/utils/request";
import md5 from 'js-md5'

export default {
  name: 'AddUser',
  data() {
    const checkAge = (value, callback) => {
      if (!/^[0-9]+$/.test(value)) {
        callback(new Error('请输入数字值'));
      }
      callback()
    };
    return {
      form: { sex: '男' },
      rules: {
        name: [
          { required: true, message: '请输入姓名', trigger: 'blur' }
        ],
        id: [
          { validator: checkAge, trigger: 'blur' }
        ],
        studentId: [
          { trigger: 'blur' }
        ],
        major: [
          { trigger: 'blur' }
        ],
        grade: [
          { trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    save() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          let data = JSON.parse(JSON.stringify(this.form))
          let password = md5(this.form.password + 'qingge')
          data.password = password
          console.log(data);
          request.post('/user/save', data).then(res => {
            if (res.code === '200') {
              this.$notify.success('新增成功')
              this.$refs['ruleForm'].resetFields()
            } else {
              this.$notify.error(res.msg)
            }
          })
        }
      })
    }
  }
}

</script>

